//
//  oldPublishDemandViewController.m
//  laonianbang
//
//  Created by 勇拓 李 on 18/3/10.
//  Copyright © 2018年 zaiyou. All rights reserved.
//

#import "oldPublishDemandViewController.h"
#import "oldRippleView.h"
#import "oldVoiceView.h"
#import "oldAddressChooseViewController.h"
#import "oldChooseCollectionViewController.h"
#import "oldCenterSoundsBtnView.h"
#import "QNuploader.h"
#import "oldVoiceManager.h"
#import "oldWatingViewController.h"
#import "oldMessageManager.h"
#import "oldSupporCardView.h"
#import "OrderInfoViewController.h"
#import "oldOrderInfo.h"
#import "AppDelegate.h"
#import "oldSingleServiceIconView.h"
#import "oldServiceInfoView.h"
#import "UIImageView+UIImageView_oldScrollView.h"

@interface oldPublishDemandViewController ()<oldCenterSoundsBtnViewDelegate, oldMessageDelegate, oldSupporCardViewDelegate, oldSingleServiceIconViewDelegate, UIScrollViewDelegate, oldServiceInfoViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *address_view;
@property (weak, nonatomic) IBOutlet UILabel *address_label;
@property (weak, nonatomic) IBOutlet UIView *service_view;
@property (weak, nonatomic) IBOutlet UILabel *service_label;
@property (weak, nonatomic) IBOutlet UIButton *btn_publish;
@property (weak, nonatomic) IBOutlet UIView *center_view;

@property (nonatomic, strong)oldVoiceView *voiceView;
@property (nonatomic, strong)oldCenterSoundsBtnView *centSoundsView;
@property (nonatomic, strong)oldSupporCardView *supportCardView;
@property (nonatomic, strong)UIButton *btn_del;

@property (nonatomic, strong)oldMessageManager *manager;
@property (nonatomic, strong)oldMessageManager *managerEnd;
@property (nonatomic, strong)oldMessageManager *managerFailed;
@property (nonatomic, strong)oldMessageManager *managerReject;
@property (nonatomic, strong)oldOrderInfo *orderInfo;

@property (weak, nonatomic) IBOutlet UIView *firstServiceView;
@property (nonatomic, copy)NSArray *serviceArray;
@property (weak, nonatomic) IBOutlet UIView *secondServiceView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *firstServiceView_width;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *secondServiceView_width;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *img_arrow_lead;
@property (weak, nonatomic) IBOutlet UIImageView *img_arrow;
@property (weak, nonatomic) IBOutlet UILabel *label_placeholder;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView1;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView2;
@property (nonatomic, strong)UIPageControl *pageControl1;
@property (nonatomic, strong)UIPageControl *pageControl2;
@end

@implementation oldPublishDemandViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self configServices];
    _number = 0;
    _count = 0;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self initData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (oldVoiceView *)voiceView
{
    if (!_voiceView) {
        _voiceView = [[[NSBundle mainBundle] loadNibNamed:@"oldVoiceView" owner:self options:nil] objectAtIndex:0];
        _voiceView.frame = CGRectMake(0, 0, 200, 46);
    }
    
    return _voiceView;
}

- (oldCenterSoundsBtnView *)centSoundsView
{
    if (!_centSoundsView) {
        _centSoundsView = [[[NSBundle mainBundle] loadNibNamed:@"oldCenterSoundsBtnView" owner:self options:nil] objectAtIndex:0];
        _centSoundsView.frame = CGRectMake((self.view.frame.size.width - 300 - 30)/2, 50, 300, 175);
        _centSoundsView.delegate = self;
    }
    
    return _centSoundsView;
}

- (oldSupporCardView *)supportCardView
{
    if (!_supportCardView) {
        _supportCardView = [[[NSBundle mainBundle] loadNibNamed:@"oldSupporCardView" owner:self options:nil] objectAtIndex:0];
        _supportCardView.frame = CGRectMake(0, 20, SCREEN_WIDTH - 50, 81);
        _supportCardView.delegate = self;
    }
    
    return _supportCardView;
}

- (UIButton *)btn_del
{
    if (!_btn_del) {
        _btn_del = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 125, _voiceView.frame.origin.y + 15, 80, 14)];
        [_btn_del setTitleColor:Color_With_Rgb(77,77,77,1) forState:UIControlStateNormal];
        [_btn_del setTitle:@"重新录制" forState:UIControlStateNormal];
        _btn_del.titleLabel.font = [UIFont systemFontOfSize: 15.0];
        [_btn_del addTarget:self action:@selector(btn_del_tapped:) forControlEvents:UIControlEventTouchDown];
    }
    
    return _btn_del;
}

#pragma mark - initView
- (void)initView
{
    _btn_publish.layer.cornerRadius = 5.f;
    [_btn_publish addTarget:self action:@selector(btn_publish_tapped:) forControlEvents:UIControlEventTouchDown];
    
    UITapGestureRecognizer * gestureAddress = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gesAddress:)];
    [_address_view addGestureRecognizer:gestureAddress];
    _address_view.userInteractionEnabled = YES;
    
    [self initScrollView];
    
    [self initMessage];
}

- (void)initMessage
{
    _manager = [[oldMessageManager alloc] initWithType:orderCreate];
    _manager.delegate = self;
    [_manager registerForNotifications];
    
    _managerEnd = [[oldMessageManager alloc] initWithType:orderEnd];
    _managerEnd.delegate = self;
    [_managerEnd registerForNotifications];
    
    _managerFailed = [[oldMessageManager alloc] initWithType:orderFail];
    _managerFailed.delegate = self;
    [_managerFailed registerForNotifications];
    
    _managerReject = [[oldMessageManager alloc] initWithType:orderReject];
    _managerReject.delegate = self;
    [_managerReject registerForNotifications];
}

- (void)initScrollView
{
    _scrollView1.delegate = self;
    _scrollView1.pagingEnabled = YES;
    [_scrollView1 setShowsVerticalScrollIndicator:NO];
    [_scrollView1 setShowsHorizontalScrollIndicator:NO];
    
    _scrollView2.delegate = self;
    [_scrollView2 setShowsVerticalScrollIndicator:NO];
    _scrollView2.tag = noDisableHorizontalScrollTag;
}

#pragma mark - configServices
- (void)configServices
{
    WeakSelf
    
    _img_arrow.hidden = YES;
    _secondServiceView.backgroundColor = [UIColor whiteColor];
    [oldHub waiting:@"加载服务信息中.."];
    
    [OLDNetWork httpRequestWithPostPut:URL_GetAllServeCategory params:@{@"pid":@"0"} success:^(id data) {
        [oldHub hideHUD];
        if ([data count]) {
            [weakSelf initServicesArray:data];
        }
        weakSelf.img_arrow.hidden = NO;
        weakSelf.secondServiceView.backgroundColor = Color_With_Rgb(234, 234, 234, 1);
    } error:^(NSString *error) {
        [oldHub warningUser:error];
    }];
}

- (void)initServicesArray:(id)data
{
    NSMutableArray *array = [NSMutableArray array];
    
    for (int i = 0; i < [data count]; i++) {
        oldService *service = [[oldService alloc] initWithDictionary:data[i]];
        [array addObject:service];
    }
    
    _serviceArray = array;
    
    [self initTopView];
}

- (void)initTopView
{
    _firstServiceView_width.constant = SCREEN_WIDTH/4 * [_serviceArray count];
    [_firstServiceView layoutIfNeeded];
    
    for (int i = 0; i < [_serviceArray count]; i++) {
        oldSingleServiceIconView *view = [[[NSBundle mainBundle] loadNibNamed:@"oldSingleServiceIconView" owner:self options:nil] objectAtIndex:0];
        view.service = _serviceArray[i];
        view.delegate = self;
        view.index = i;
        view.frame = CGRectMake(SCREEN_WIDTH/4 * i, 0, SCREEN_WIDTH/4, 69);
        [_firstServiceView addSubview:view];
    }
    
    [self initControl1];
    
    if ([_serviceArray count]) {
        oldService *service = _serviceArray[0];
        [self initSubTopView:service.childList];
    }
}

- (void)initSubTopView:(NSArray *)array
{
    for (UIView *subView in _secondServiceView.subviews) {
        if ([subView isKindOfClass:[oldSingleServiceIconView class]]) {
            [subView removeFromSuperview];
        }
    }
    
    _secondServiceView_width.constant = SCREEN_WIDTH/4 * [array count];
    [_secondServiceView layoutIfNeeded];
    
    for (int i = 0; i < [array count]; i++) {
        oldSingleServiceIconView *view = [[[NSBundle mainBundle] loadNibNamed:@"oldSingleServiceIconView" owner:self options:nil] objectAtIndex:0];
        view.service = array[i];
        view.delegate = self;
        view.frame = CGRectMake(SCREEN_WIDTH/4 * i, 0, SCREEN_WIDTH/4, 69);
        [_secondServiceView addSubview:view];
    }
    
    [_scrollView2 flashScrollIndicators];
}

- (void)initControl1
{
    _pageControl1 = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 55 , self.view.frame.size.width, 40)];
    [_pageControl1 setCurrentPage:0];
    _pageControl1.numberOfPages = [_serviceArray count]/4 + 1;//指定页面个数
    [_pageControl1 setBackgroundColor:[UIColor clearColor]];
    _pageControl1.currentPageIndicatorTintColor = OLD_COLOR;
    _pageControl1.pageIndicatorTintColor = Color_With_Rgb(229, 229, 229, 1);
    _pageControl1.userInteractionEnabled = NO;
    [_scrollView1.superview addSubview:_pageControl1];
}

#pragma mark - topviewDelegate
- (void)singleIconViewTapped:(oldService *)service
{
    oldServiceInfoView *view = [[[NSBundle mainBundle] loadNibNamed:@"oldServiceInfoView"
                                                      owner:self
                                                    options:nil] objectAtIndex:0];
    view.service = service;
    view.delegate = self;
}

- (void)changeSubView:(NSArray *)array index:(NSInteger)index
{
    _img_arrow_lead.constant = (SCREEN_WIDTH/4 - 17)/2 + index * SCREEN_WIDTH/4;
    [self initSubTopView:array];
}

#pragma mark - scrollView - delegate
- (void)scrollViewDidScroll:(UIScrollView *)sender{
    
    if (sender == _scrollView1)
    {
        int page = (_scrollView1.contentOffset.x + SCREEN_WIDTH/2)/ (SCREEN_WIDTH);//通过滚动的偏移量来判断目前页面所对应的小白点
        _pageControl1.currentPage = page;//pagecontroll响应值的变化
    }
}

#pragma mark - initData
- (void)initData
{
    WeakSelf
    
    [OLDNetWork httpRequestWithPostPut:URL_OLD_GetCurrentOrder params:nil success:^(id data) {
        [oldHub hideHUD];
        if ([data isKindOfClass:[NSArray class]]) {
            weakSelf.orderInfo = nil;
            weakSelf.ifSearching = YES;
        }
        else if(data && ![data isKindOfClass:[NSNull class]])
        {
            weakSelf.orderInfo = [[oldOrderInfo alloc] initWithDictionary:data];
            weakSelf.ifSearching = NO;
        }
        else
        {
            weakSelf.orderInfo = nil;
            weakSelf.ifSearching = NO;
        }
        [weakSelf initCenterView];
    } error:^(NSString *error) {
        [oldHub warningUser:error];
    }];
}

#pragma mark - address
- (void)gesAddress:(id)sender
{
    oldAddressChooseViewController *vc = [oldAddressChooseViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setAddressInfo:(oldAddressInfo *)addressInfo
{
    _addressInfo = addressInfo;
    _address_label.text = addressInfo.address;
}

#pragma mark - service
//- (void)gesService:(id)sender
//{
//    oldChooseCollectionViewController *vc = [[oldChooseCollectionViewController alloc] initWithNibName:@"oldChooseCollectionViewController" bundle:nil];
//    vc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:vc animated:YES];
//}

- (void)setServiceInfo:(oldService *)serviceInfo
{
    _serviceInfo = serviceInfo;
    _service_label.text = [NSString stringWithFormat:@"当前选择服务：%@", serviceInfo.cname];
}

- (void)chooseService:(oldService *)service
{
    self.serviceInfo = service;
}

#pragma mark - centerView
- (void)initCenterView
{
    if (_orderInfo) {
        [self voiceRemove];
        [self.centSoundsView removeFromSuperview];
        [_center_view addSubview:self.supportCardView];
        self.supportCardView.orderInfo = _orderInfo;
        _btn_publish.hidden = YES;
        _ifSearching = NO;
        _number = 0;
        _count = 0;
    }
    else if (_ifSearching && !_orderInfo)
    {
        [self voiceRemove];
        [self.centSoundsView removeFromSuperview];
        
        [_btn_publish setTitle:@"寻找中.." forState:UIControlStateNormal];
        _btn_publish.hidden = NO;
    }
    else
    {
        [_supportCardView removeFromSuperview];
        [_center_view addSubview:self.centSoundsView];
        [_btn_publish setTitle:@"发布服务" forState:UIControlStateNormal];
        _btn_publish.hidden = NO;
    }
}

- (void)oldCenterSoundsBtnClick:(BOOL)on error:(BOOL)isError
{
    if (on) {
        [self voiceRemove];
    }
    else
    {
        if (!isError) {
            [self voiceAdd];
        }
    }
}

- (void)btn_del_tapped:(id)sender
{
    [self voiceRemove];
}

- (void)oldSupporCardViewTapped
{
    OrderInfoViewController *vc = [OrderInfoViewController new];
    vc.orderInfo = _orderInfo;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)voiceRemove
{
    [self.voiceView removeView];
    [self.btn_del removeFromSuperview];
    _label_placeholder.hidden = NO;
}

- (void)voiceAdd
{
    [_center_view addSubview:self.voiceView];
    [_center_view addSubview:self.btn_del];
    [_voiceView beginWithRecord];
    _label_placeholder.hidden = YES;
}

#pragma mark - message
- (void)receiveMessage:(id)message type:(oldMessageType)type
{
    [self initData];
    
    if (type == orderCreate || type == orderEnd) {
        [oldHub waiting:@"获取订单中信息.."];
    }
    else
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"订单失败" message:message preferredStyle: UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        
        [alertController addAction:action];
        
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - lastBtn
- (void)btn_publish_tapped:(id)sender
{
    if (_ifSearching) {
        [self gotoWating];
        return;
    }
    
    if (!_addressInfo.aid) {
        [oldHub warningUser:@"请选择服务地址！"];
        return;
    }
    
    if([_voiceView superview])
    {
        WeakSelf
        [oldHub waiting:@"服务发布中.."];
        [QiNiuShareInstance uploadImageToQNFilePath:[oldVoice changeCafToMp3] type:Voice_file block:^(NSString *url) {
            if (url) {
                [weakSelf publish:url];
            }
            else
            {
                [oldHub warningUser:@"服务发送失败请重试"];
            }
        }];
    }
    else
    {
        if (!_serviceInfo.cid) {
            [oldHub warningUser:@"请选择服务类型或者录入语音信息！"];
            return;
        }
        
        [oldHub waiting:@"服务发布中.."];
        
        WeakSelf
        
        NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: _serviceInfo.cid, @"cid",  _addressInfo.aid, @"aid",nil];
        
        [OLDNetWork httpRequestWithPostPut:URL_SendRequest params:params success:^(id data) {
            [oldHub hideHUD];
            [weakSelf gotoWating];
        } error:^(NSString *error) {
            [oldHub warningUser:error];
        }];
    }
}

#pragma mark - network
- (void)publish:(NSString *)url
{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:_addressInfo.aid, @"aid", url, @"voiceUrl", nil];
    if (_serviceInfo.cid) {
        [params setObject:_serviceInfo.cid forKey:@"cid"];
    }
    
    WeakSelf
    
    [OLDNetWork httpRequestWithPostPut:URL_SendRequest params:params success:^(id data) {
        [oldHub hideHUD];
        [weakSelf gotoWating];
    } error:^(NSString *error) {
        [oldHub warningUser:error];
    }];
}

- (void)gotoWating
{
    _ifSearching = YES;
    
    oldWatingViewController *vc = [oldWatingViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    vc.number = _number;
    vc.count = _count;
    [self.navigationController pushViewController:vc animated:YES];
    _btn_publish.titleLabel.text = @"寻找中..";
    [_btn_publish setTitle:@"寻找中.." forState:UIControlStateNormal];
}

@end
